import datetime
import uuid
import jwt
import oss2
import requests
from django.db import transaction


from django.contrib.auth.hashers import check_password
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from boss_backend import settings
from enterprise.models import Recruiter, CCompany, Job


# Create your views here.
class ImageUploadView(APIView):
    def post(self, request):
        """
        通用图片上传到阿里云OSS
        请求体：form-data格式，key为"image_file"，value为图片文件
        参数：type (可选) - 指定图片类型：avatar-头像, logo-企业logo, license-营业执照
        """
        # 1. 获取前端上传的图片文件和类型
        image_file = request.FILES.get("image_file")
        image_type = request.data.get("type", "avatar")  # 默认为头像

        if not image_file:
            return Response(
                {"error": "请选择要上传的图片文件"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2. 验证文件类型
        allowed_types = ["image/jpeg", "image/png"]
        if image_file.content_type not in allowed_types:
            return Response(
                {"error": "仅支持JPG、PNG格式的图片"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 3. 根据类型设置不同的存储目录
        oss_config = settings.ALIYUN_OSS_CONFIG
        auth = oss2.Auth(oss_config["ACCESS_KEY_ID"], oss_config["ACCESS_KEY_SECRET"])
        bucket = oss2.Bucket(auth, oss_config["ENDPOINT"], oss_config["BUCKET_NAME"])

        # 设置不同的目录
        dir_mapping = {
            "avatar": "recruiter-avatars/",  # 个人头像
            "logo": "company-logos/",  # 企业Logo
            "license": "business-licenses/"  # 营业执照
        }

        storage_dir = dir_mapping.get(image_type, "others/")
        file_ext = image_file.name.split(".")[-1].lower()
        unique_filename = f"{uuid.uuid4()}.{file_ext}"
        oss_file_path = f"{storage_dir}{unique_filename}"

        # 4. 上传到OSS
        try:
            result = bucket.put_object(
                oss_file_path,
                image_file,
                headers={"Content-Type": image_file.content_type}
            )

            if result.status == 200:
                image_url = f"https://{oss_config['BUCKET_NAME']}.{oss_config['ENDPOINT']}/{oss_file_path}"
                return Response({
                    "status": "success",
                    "image_url": image_url,
                    "image_type": image_type
                })
            else:
                return Response({"error": "图片上传失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        except Exception as e:
            return Response(
                {"error": f"OSS上传异常：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class LoginView(APIView):
    def post(self, request):
        """
        登录并获取token
        请求体：{"username": "账号", "password": "密码"}
        返回：token + 是否首次登录（is_complete）
        """
        username = request.data.get("username")
        password = request.data.get("password")
        #1234

        if not all([username, password]):
            return Response(
                {"error": "用户名和密码不能为空"},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            recruiter = Recruiter.objects.get(username=username)
        except Recruiter.DoesNotExist:
            return Response(
                {"error": "用户名不存在"},
                status=status.HTTP_401_UNAUTHORIZED
            )

        # 验证密码（加密比对）
        if password != recruiter.password:
            return Response(
                {"error": "密码错误"},
                status=status.HTTP_401_UNAUTHORIZED
            )

        # 生成JWT（包含recruiter_id）
        JWT_SECRET = getattr(settings, "JWT_SECRET", "your-secret-key")
        expiration = datetime.datetime.utcnow() + datetime.timedelta(hours=24)
        token = jwt.encode(
            {"recruiter_id": recruiter.id, "exp": expiration},
            JWT_SECRET,
            algorithm="HS256"
        )

        return Response({
            "status": "success",
            "token": token,
            "is_complete": recruiter.is_complete  # 前端根据此字段判断是否跳转完善页面
        })

class PersonalInfoView(APIView):
    def post(self, request):
        """
        暂存个人信息（仅验证字段，不保存到数据库，等企业认证成功后再落地）
        请求头：Authorization: Bearer <token>
        请求体：{"name": "姓名", "avatar": "头像URL", "position": "职位"}
        """
        # 1. 验证token获取用户
        token = request.META.get("HTTP_AUTHORIZATION", "").split(" ")[-1]
        if not token:
            return Response({"error": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        try:
            payload = jwt.decode(
                token, getattr(settings, "JWT_SECRET", "your-secret-key"), algorithms=["HS256"]
            )
            recruiter_id = payload["recruiter_id"]
            recruiter = Recruiter.objects.get(id=recruiter_id)
        except Exception:
            return Response({"error": "登录无效"}, status=status.HTTP_401_UNAUTHORIZED)

        # 2. 验证个人信息字段（仅校验，不保存）
        name = request.data.get("name")
        avatar = request.data.get("avatar")
        position = request.data.get("position")
        if not all([name, avatar, position]):
            return Response(
                {"error": "姓名、头像、职位不能为空"}, status=status.HTTP_400_BAD_REQUEST
            )

        # 3. 仅返回成功提示，将数据暂存到前端（或后续通过token关联）
        # 前端需存储这些信息，等企业认证时一起传给CompanyInfoView
        return Response({
            "status": "success",
            "message": "个人信息验证通过，请继续完善企业信息",
            "data": {
                "recruiter_id": recruiter.id,
                "name": name,
                "avatar": avatar,
                "position": position
            }
        })

# 3. 企业信息完善接口（第二步，最终完成后跳转主页面）
class CompanyInfoView(APIView):
    def post(self, request):
        """
        企业信息完善+认证（含事务：个人信息+企业信息原子保存）
        请求头：Authorization: Bearer <token>
        请求体：{
            "personal": {"name": "姓名", "avatar": "头像URL", "position": "职位"},  # 前端暂存的个人信息
            "company": {
                "name": "企业全称", "short_name": "简称", "scale": "规模", ...,
                "business_license": "工商号", "logo": "Logo URL", "license_image": "执照URL"
            }
        }
        """
        # 1. 验证登录态
        token = request.META.get("HTTP_AUTHORIZATION", "").split(" ")[-1]
        if not token:
            return Response({"error": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
        try:
            payload = jwt.decode(
                token, getattr(settings, "JWT_SECRET", "your-secret-key"), algorithms=["HS256"]
            )
            recruiter_id = payload["recruiter_id"]
            recruiter = Recruiter.objects.get(id=recruiter_id)
        except Exception:
            return Response({"error": "登录无效"}, status=status.HTTP_401_UNAUTHORIZED)

        # 2. 提取并验证前端传递的所有数据（个人信息+企业信息）
        personal_data = request.data.get("personal", {})  # 个人信息（前端暂存的）
        company_data = request.data.get("company", {})    # 企业信息

        # 2.1 验证个人信息（必传）
        personal_required = ["name", "avatar", "position"]
        personal_missing = [f for f in personal_required if not personal_data.get(f)]
        if personal_missing:
            return Response(
                {"error": f"个人信息缺失：{', '.join(personal_missing)}"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2.2 验证企业信息（必传）
        company_required = ["name", "short_name", "scale", "description", "address", "industry", "business_license"]
        company_missing = [f for f in company_required if not company_data.get(f)]
        if company_missing:
            return Response(
                {"error": f"企业信息缺失：{', '.join(company_missing)}"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 3. 调用梦远数据API验证工商号（不变）
        api_url = "https://www.apimy.cn/api/release/base"
        api_params = {
            "name": company_data["name"],
            "key": "7FjZrOYtnaPvRY7eTGVnV9FUVJpfoG"  # 按实际情况调整
        }
        try:
            response = requests.get(api_url, params=api_params)
            api_data = response.json()
            if api_data.get("code") != 200:
                return Response(
                    {"error": f"工商API调用失败：{api_data.get('msg', '未知错误')}"},
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
            api_license = api_data.get("data", {}).get("CreditNo", "")
            if not api_license:
                return Response(
                    {"error": "工商API未返回有效工商号"},
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
            # 对比工商号
            user_license = company_data["business_license"].strip()
            if user_license != api_license:
                return Response(
                    {"error": "企业认证失败：工商号与官方信息不一致"},
                    status=status.HTTP_400_BAD_REQUEST
                )
        except Exception as e:
            return Response(
                {"error": f"工商API调用异常：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

        # 4. 验证企业枚举字段（不变）category
        valid_scales = [c[0] for c in CCompany.COMPANY_SCALE]
        if company_data["scale"] not in valid_scales:
            return Response(
                {"error": f"公司规模无效，可选：{', '.join(valid_scales)}"},
                status=status.HTTP_400_BAD_REQUEST
            )
        valid_industries = [c[0] for c in CCompany.INDUSTRY_CHOICES]
        if company_data["industry"] not in valid_industries:
            return Response(
                {"error": f"行业无效，可选：{', '.join(valid_industries)}"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 5. 事务：原子保存个人信息+企业信息（核心步骤）
        try:
            with transaction.atomic():
                # 5.1 保存个人信息（更新Recruiter表）
                recruiter.name = personal_data["name"]
                recruiter.avatar = personal_data["avatar"]
                recruiter.position = personal_data["position"]
                recruiter.is_complete = True  # 标记信息完善
                recruiter.save()

                # 5.2 保存企业信息（创建CCompany表）
                company = CCompany.objects.create(
                    recruiter=recruiter,  # 关联招聘者
                    name=company_data["name"],
                    short_name=company_data["short_name"],
                    scale=company_data["scale"],
                    description=company_data["description"],
                    address=company_data["address"],
                    industry=company_data["industry"],
                    logo=company_data.get("logo", ""),
                    business_license=company_data["business_license"],
                    license_image=company_data.get("license_image", ""),
                    is_verified=True  # 认证通过
                )

            # 事务成功：返回结果
            return Response({
                "status": "success",
                "message": "企业认证通过，个人+企业信息已保存",
                "data": {
                    "recruiter_id": recruiter.id,
                    "company_id": company.id,
                    "is_complete": recruiter.is_complete
                }
            })
        except Exception as e:
            # 事务失败：自动回滚（个人和企业信息都不会保存）
            return Response(
                {"error": f"数据保存失败（已回滚）：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class MainPageView(APIView):
    def get(self, request):
        """
        获取主页面数据（头像、姓名及关联企业信息）
        请求头：Authorization: Bearer <token>
        """
        # 提取并验证token
        auth_header = request.META.get("HTTP_AUTHORIZATION", "")
        if not auth_header.startswith("Bearer "):
            return Response({"error": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)

        token = auth_header.split(" ")[-1]
        if not token:
            return Response({"error": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            # 解码token获取招聘者ID
            payload = jwt.decode(
                token,
                getattr(settings, "JWT_SECRET", "your-secret-key"),
                algorithms=["HS256"]
            )
            recruiter_id = payload.get("recruiter_id")
            if not recruiter_id:
                return Response({"error": "登录信息无效"}, status=status.HTTP_401_UNAUTHORIZED)

            # 获取招聘者信息
            recruiter = Recruiter.objects.get(id=recruiter_id)

        except jwt.ExpiredSignatureError:
            return Response({"error": "登录已过期"}, status=status.HTTP_401_UNAUTHORIZED)
        except jwt.InvalidTokenError:
            return Response({"error": "无效的登录凭证"}, status=status.HTTP_401_UNAUTHORIZED)
        except Recruiter.DoesNotExist:
            return Response({"error": "用户不存在"}, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as e:
            return Response({"error": f"登录验证失败：{str(e)}"}, status=status.HTTP_401_UNAUTHORIZED)

        # 反向查询：获取当前招聘者关联的所有企业（通过related_name='companies'）
        # 通常一个招聘者对应一个企业，这里取第一个
        company = recruiter.companies.first()  # 若没有关联企业，返回None

        # 构建企业信息（若存在）
        company_info = None
        if company:
            company_info = {
                "name": company.name,
                "short_name": company.short_name,
                "scale": company.scale,
                "description": company.description,
                "address": company.address,
                "industry": company.industry,
                "logo": company.logo,
                "business_license": company.business_license,
                # "license_image": company.license_image,营业执照图片
                "is_verified": company.is_verified
            }

        return Response({
            "user_info": {
                "name": recruiter.name,
                "avatar": recruiter.avatar,
                "position": recruiter.position  # 可选：补充职务信息
            },
            "company_info": company_info  # 若无企业，返回null
        })


# 5. 公司详情接口（公开访问，无需登录）
class CompanyDetailView(APIView):
    """
    获取公司详情（根据公司ID）
    GET /enterprise/company/<company_id>/
    """
    permission_classes = []  # 公开访问
    
    def get(self, request, company_id=None):
        try:
            company = CCompany.objects.get(id=company_id)
            
            # 获取该公司发布的职位
            jobs = Job.objects.filter(
                company=company, status='published'
            ).order_by('-published_at')[:10]
            jobs_data = []
            for job in jobs:
                jobs_data.append({
                    "id": job.id,
                    "title": job.title,
                    "salary": job.salary_range,
                    "experience": job.experience_requirement,
                    "education": job.education_requirement,
                    "skills": job.requirements[:100] if job.requirements else "",  # 简化的技能描述
                    "publisher": job.publisher.name if job.publisher else "HR",
                    "publishTime": self._format_time(job.published_at) if job.published_at else "未知"
                })
            
            company_data = {
                "id": company.id,
                "name": company.name,
                "short_name": company.short_name,
                "logo": company.logo or "/upload/img.png",
                "status": "已上市" if company.is_verified else "未认证",
                "industry": (
                    company.get_industry_display()
                    if hasattr(company, 'get_industry_display')
                    else company.industry
                ),
                "size": (
                    company.get_scale_display()
                    if hasattr(company, 'get_scale_display')
                    else company.scale
                ),
                "location": (
                    company.address.split('·')[0]
                    if '·' in company.address
                    else (
                        company.address.split('市')[0] + '市'
                        if '市' in company.address
                        else company.address
                    )
                ),
                "introduction": (
                    company.description[:100] + "..."
                    if len(company.description) > 100
                    else company.description
                ),
                "description": company.description,
                "address": company.address,
                "welfare": ["五险一金", "补充医疗保险", "年终奖", "带薪年假"],  # 默认福利
                "jobs": jobs_data,
                "news": []  # 公司动态暂时为空
            }
            
            return Response({
                "code": 200,
                "message": "获取成功",
                "data": company_data
            })
            
        except CCompany.DoesNotExist:
            return Response({
                "code": 404,
                "message": f"公司ID {company_id} 不存在"
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                "code": 500,
                "message": f"获取公司详情失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def _format_time(self, dt):
        """格式化时间为相对时间"""
        if not dt:
            return "未知"
        from django.utils import timezone
        now = timezone.now()
        delta = now - dt
        if delta.days == 0:
            return "今天"
        elif delta.days == 1:
            return "1天前"
        elif delta.days < 7:
            return f"{delta.days}天前"
        else:
            return dt.strftime("%Y-%m-%d")

# 4. 主页面数据接口（用于测试最终数据展示）
# class MainPageView(APIView):
#     def get(self, request):
#         """
#         获取主页面数据（头像、姓名等）
#         请求头：Authorization: Bearer <token>
#         """
#         token = request.META.get("HTTP_AUTHORIZATION", "").split(" ")[-1]
#         if not token:
#             return Response({"error": "请先登录"}, status=status.HTTP_401_UNAUTHORIZED)
#
#         try:
#             payload = jwt.decode(
#                 token,
#                 getattr(settings, "JWT_SECRET", "your-secret-key"),
#                 algorithms=["HS256"]
#             )
#             recruiter = Recruiter.objects.get(id=payload["recruiter_id"])
#         except Exception:
#             return Response({"error": "登录无效"}, status=status.HTTP_401_UNAUTHORIZED)
#
#         return Response({
#             "user_info": {
#                 "name": recruiter.name,
#                 "avatar": recruiter.avatar
#             },
#             "company_info": {
#                  "name": recruiter.company.name if hasattr(recruiter, "company") else None,
#                  "short_name": recruiter.company.short_name if hasattr(recruiter, "company") else None,
#                  "scale": recruiter.company.scale if hasattr(recruiter, "company") else None,
#                  "description": recruiter.company.description if hasattr(recruiter, "company") else None,
#                  "address": recruiter.company.address if hasattr(recruiter, "company") else None,
#                  "industry": recruiter.company.industry if hasattr(recruiter, "company") else None,
#                  "logo": recruiter.company.logo if hasattr(recruiter, "company") else None,
#                  "business_license": recruiter.company.business_license if hasattr(recruiter, "company") else None,
#                  "license_image": recruiter.company.license_image if hasattr(recruiter, "company") else None,
#                  "is_verified": recruiter.company.is_verified if hasattr(recruiter, "company") else None
#             }
#         })



# 6. 职位列表（公开访问）
class JobsListView(APIView):
    permission_classes = []  # 公开访问

    def get(self, request):
        """
        获取职位列表（默认返回已发布职位，按发布时间倒序）
        GET /enterprise/jobs/?search=xxx&page=1&size=20
        """
        try:
            search = request.query_params.get('search', '').strip()
            page = int(request.query_params.get('page', 1))
            size = int(request.query_params.get('size', 20))
            page = 1 if page <= 0 else page
            size = 20 if size <= 0 or size > 100 else size

            qs = Job.objects.filter(status='published').order_by('-published_at')
            if search:
                from django.db.models import Q
                qs = qs.filter(
                    Q(title__icontains=search) |
                    Q(description__icontains=search) |
                    Q(requirements__icontains=search) |
                    Q(company__name__icontains=search) |
                    Q(company__short_name__icontains=search)
                )

            total = qs.count()
            start = (page - 1) * size
            jobs = qs[start:start + size]

            def map_job(job):
                return {
                    "id": job.id,
                    "title": job.title,
                    "salary": job.salary_range,
                    "experience": job.experience_requirement,
                    "education": job.education_requirement,
                    "skills": self._extract_skills(job),
                    "company": job.company.short_name or job.company.name,
                    "location": job.work_city,
                    "requirements": job.requirements,
                    "description": job.description,
                    "published_at": self._format_time(job.published_at) if job.published_at else "",
                }

            data = [map_job(j) for j in jobs]
            return Response({
                "code": 200,
                "data": data,
                "pagination": {
                    "page": page,
                    "size": size,
                    "total": total
                }
            })
        except Exception as e:
            return Response({"error": f"服务器错误：{str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def _extract_skills(self, job):
        text = (job.requirements or "") + " " + (job.description or "")
        keywords = ['Java','Python','JavaScript','TypeScript','Vue','React','Angular','Spring','Spring Boot',
                    'Spring Cloud','MyBatis','Hibernate','MySQL','Redis','Elasticsearch','Kafka','Docker',
                    'Kubernetes','Golang','Go','C++','C#','.NET','Linux']
        return [k for k in keywords if k in text]

    def _format_time(self, dt):
        try:
            return dt.strftime("%Y-%m-%d %H:%M")
        except Exception:
            return ""


# 7. 职位详情（公开访问）
class JobDetailView(APIView):
    permission_classes = []  # 公开访问

    def get(self, request, job_id: int):
        try:
            job = Job.objects.get(id=job_id, status='published')
            data = {
                "id": job.id,
                "title": job.title,
                "salary": job.salary_range,
                "experience": job.experience_requirement,
                "education": job.education_requirement,
                "skills": JobsListView()._extract_skills(job),
                "company": {
                    "id": job.company.id,
                    "name": job.company.name,
                    "short_name": job.company.short_name,
                    "logo": job.company.logo,
                },
                "location": job.work_city,
                "requirements": job.requirements,
                "description": job.description,
                "benefits": job.benefits,
                "published_at": JobsListView()._format_time(job.published_at) if job.published_at else "",
            }
            return Response({"code": 200, "data": data})
        except Job.DoesNotExist:
            return Response({"error": "职位不存在或未发布"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({"error": f"服务器错误：{str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)





